package com.mastercard.labs

import org.apache.shiro.SecurityUtils;
import org.springframework.dao.DataIntegrityViolationException

class RedemptionController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def redemptionService;
	def voucherService;
	def emailService
	def smsService
	def dealService
	
    def index() {
        //redirect(action: "search", params: params)
		render(view: "search")
    }
	
	def search() {
		log.info 'search redemption method'
		flash.message = null
		//redirect(action: "search", params: params)
		//if(params.search == "Search"){
//		params.searchInd = "true"
		def p = perform()
		log.info (p)
		render(view: "search", model: p + params)
		//}
	}
	
	def getVoucher() {
		log.info 'redemption get voucher method'
		def userInstance = SecurityUtils.subject.session.getAttribute("current_user")
		def reward = RewardPoint.findByUser(userInstance)
		//		reward.lock()
		def rewardPoint = reward?.getPoint()?:0
		def voucherInstanceList = voucherService.searchByCondition(params.searchTitle, params.searchCountry, params.searchMerchant, params.searchCategories, new Date());
		
		render (view: "searchvoucher", model: [voucherInstanceList: voucherInstanceList,
		searchTitle: params.searchTitle,
		searchMerchant: params.searchMerchant,
		searchCategories: params.searchCategories,
		searchCountry: params.searchCountry,
		rewardPoint: rewardPoint,
		deals: dealService.getDeals(userInstance)
		])
	}
	
	def redemption() {
		log.info 'redemption redemption method'
		log.info (params)
		def voucher_id = params.get("voucher_id")
		def quantities_no = params.get("redptQuantity" + voucher_id)
		def userInstance = SecurityUtils.subject.session.getAttribute("current_user")
		def voucher = Voucher.lock(voucher_id)
//		voucher.lock()
		def reward = RewardPoint.findByUser(userInstance, [lock: true])
//		reward.lock()
		def rewardPoint = reward?.getPoint()?:0
		
		def remainingPoint = rewardPoint - voucher.getRdptPoint() * Integer.parseInt(quantities_no)
		def remainingVoucherQuantity = voucher.getTotalQuantity() - Integer.parseInt(quantities_no)
		
		if (remainingPoint < 0 ) {
			flash.error = message(code: 'redemption.invalid.point.message')
			flash.message = null
		}else if ( remainingVoucherQuantity < 0){
			flash.error = message(code: 'redemption.invalid.voucherquantity.message')
			flash.message = null
		}else {
			voucher.setTotalQuantity(remainingVoucherQuantity)
			reward.setPoint(remainingPoint)
			redemptionService.redemptionSave(reward, voucher)
			rewardPoint = remainingPoint
			def appURL = grailsApplication.config.grails.appURL
			def qrtext1 = voucher.id + '_' + quantities_no
			String qrcodeLink = "${appURL}qrcode/text?text=${qrtext1}"
			log.info "send redemption email confirmation"
			try{
				mailService.sendMail {
					to user.email
					from "mpems.mastercard@gmail.com"
					subject "MasterCard MPEMS Notification"
					body "Dear user, \n Vourcher redeemped successful, click below link for QR Code. \n${qrcodeLink}\n\nRegerds\nMasterCard-MPEMS"
				 }
			}
			catch (e){
				log.info("email failed to send")
			}
			
			if(userInstance.smsNotification){
				log.info "send redemption sms confirmation"
				smsService.send(userInstance.mobile, qrcodeLink)
			}
			//send email to customer
			
			
			flash.message = message(code: 'redemption.updated.message', args: [voucher.title, quantities_no])
			[qrtext:qrtext1]
		}
		
		
//		def cards = cardService.getCards(userInstance)
//		redirect(action: "getVoucher", params: params)
		def voucherInstanceList = voucherService.searchByCondition(params.searchTitle, params.searchCountry, params.searchMerchant, params.searchCategories, new Date());
		
		render (view: "searchvoucher", model: [voucherInstanceList: voucherInstanceList,
		searchTitle: params.searchTitle,
		searchMerchant: params.searchMerchant,
		searchCategories: params.searchCategories,
		searchCountry: params.searchCountry,
		rewardPoint: rewardPoint
		])
	}
	
	def searchvoucher() {
		log.info 'redemption search voucher method'
		def userInstance = SecurityUtils.subject.session.getAttribute("current_user")
		def reward = RewardPoint.findByUser(userInstance)
		//		reward.lock()
		def rewardPoint = reward?.getPoint()?:0
		[rewardPoint: rewardPoint, deals: dealService.getDeals(userInstance)]
		//redirect(view: "searchvoucher", params: params)
	}
	
	private def perform(){
		def instanceList = redemptionService.searchByCondition(params.searchRedmptDate, params.searchStatus)
		//def searchCondition = params.searchRedmptDate + "#" + params.searchStatus + "#NA#"
		
		[instanceList: instanceList,
		 //searchCondition: searchCondition,
		 searchInd: "true",
		 searchRedmptDate: params.searchRedmptDate,
		 searchStatus: params.searchStatus
		]
	}

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [redemptionInstanceList: Redemption.list(params), redemptionInstanceTotal: Redemption.count()]
    }

    def create() {
        [redemptionInstance: new Redemption(params)]
    }

    def save() {
        def redemptionInstance = new Redemption(params)
        if (!redemptionInstance.save(flush: true)) {
            render(view: "create", model: [redemptionInstance: redemptionInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'redemption.label', default: 'Redemption'), redemptionInstance.id])
        redirect(action: "show", id: redemptionInstance.id)
    }

    def show() {
        def redemptionInstance = Redemption.get(params.id)
        if (!redemptionInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'redemption.label', default: 'Redemption'), params.id])
            redirect(action: "list")
            return
        }

        [redemptionInstance: redemptionInstance]
    }

    def edit() {
        def redemptionInstance = Redemption.get(params.id)
        if (!redemptionInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'redemption.label', default: 'Redemption'), params.id])
            redirect(action: "search")
            return
        }

        [redemptionInstance: redemptionInstance]
    }

    def update() {
		log.info 'update redemption method'
		log.info params.rdmpCheckList
//        def redemptionInstance = Redemption.get(params.id)
        /*if (!redemptionInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'redemption.label', default: 'Redemption'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (redemptionInstance.version > version) {
                redemptionInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'redemption.label', default: 'Redemption')] as Object[],
                          "Another user has updated this Redemption while you were editing")
                render(view: "edit", model: [redemptionInstance: redemptionInstance])
                return
            }
        }

        redemptionInstance.properties = params

        if (!redemptionInstance.save(flush: true)) {
            render(view: "edit", model: [redemptionInstance: redemptionInstance])
            return
        }
*/
		flash.message = message(code: 'common.default.updated.message')
		def p = perform()
		log.info (p)
		render(view: "search", model: p + params)
//		redirect(action: "search", params: params)
//		perform()
//		render(view: "search", params: params)
    }

    def delete() {
        def redemptionInstance = Redemption.get(params.id)
        if (!redemptionInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'redemption.label', default: 'Redemption'), params.id])
            redirect(action: "list")
            return
        }

        try {
            redemptionInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'redemption.label', default: 'Redemption'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'redemption.label', default: 'Redemption'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
